<?php

/**
 * Description of LiveController
 *
 * @author luigi.pastore
 * @created  10-giu-2011
 */
class LiveController extends Classes_Controller
{

    public function init()
    {
	$this->model_live = new Classes_Live();
	$this->model_province = new Classes_Province();
	$this->model_artist = new Classes_Artist();
	$this->model_location = new Classes_Location();
	$this->model_live_status = new Classes_LiveStatus;
        $this->model_post = new Classes_Post;

	$this->province = $this->model_province->fetchAll();
        $this->layout->province = $this->province;
	$this->layout->live_status = $this->model_live_status->fetchAll();
	
	$this->days = $this->getResource( 'Days' );
        $this->layout->days = $this->days;
	
	$this->months = $this->getResource( 'Months' );
        $this->layout->months = $this->months;
        
	$this->contact_roles		= $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles	= $this->contact_roles;
        
	// Edit...
	if( is_numeric( $id = $this->getParam( 'id' ) ) )
	{
	    // Fetch
	    $live = $this->model_live->fetchById( array( $id ) );

	    if( empty( $live ) )
		throw new Classes_Exceptions( 'Nessun id' );
	    
	    $this->live = array_shift( $live );

	    # Assegniamo i dati al layout
	    $this->layout->data = $this->live;
	    $this->layout->live_id = $this->live['live_id'];
	    
	    // Se sto editando precompilo la sessione
	    if( !empty( $this->live ) AND empty( $_SESSION['Live'] ) AND ( $this->getAction() != 'riepilogo' ) )
	    {

		# Formattiamo campi
		list( $this->live['live_date_d'], $this->live['live_date_m'], $this->live['live_date_y'] )	    = explode( '-', $this->live['live_date_ita'] );
		list( $this->live['live_stagetime_h'], $this->live['live_stagetime_m'] )    = explode( 'h', $this->live['live_stagetime_ita'] );
		list( $this->live['live_loadin_h'], $this->live['live_loadin_m'] )          = explode( 'h', $this->live['live_loadin_ita'] );
		list( $this->live['live_soundcheck_h'], $this->live['live_soundcheck_m'] )  = explode( 'h', $this->live['live_soundcheck_ita'] );
		list( $this->live['live_doorsopen_h'], $this->live['live_doorsopen_m'] )    = explode( 'h', $this->live['live_doorsopen_ita'] );
		list( $this->live['live_price_1'], $this->live['live_price_2'] )	    = explode( ',', $this->live['live_price'] );
		
		//unset( $_SESSION['Live'] ['live_artists'] );
		
		$_SESSION['Live']['Info'] = $this->live;
		$_SESSION['Live']['Artists'] = $this->live['artists'];
		$_SESSION['Live']['Location'] = $this->live['location'];
	    }
	}
        
        // Dati Form
        $this->form_data = $this->getParams();
        
        $this->layout->province = $this->province;
    }

    public function indexAction()
    {
	$this->layout->live_list = $this->model_live->fetchAll( array( 'orderby' => array( 'live_date' => 'asc' ) ) );
	$this->layout->content = array( 'script' => 'live/index' );
    }
    
    public function artistiAction()
    {
	// Se sto editando precompilo la sessione
	if( !empty( $this->live ) AND empty( $_SESSION['Live']['Artists'] ) )
	{
	    $_SESSION['Live']['Artists'] = $this->live['artists'];
	}

	if( $this->form_data['conferma'] AND $this->form_data['conferma'] !== '' )
	{

	    $_SESSION['Live']['Artists'] = array( );

	    if( count( $this->form_data['artists'] ) < 1 )
		$errorMsg = sprintf( ERR_EMPTY_SELECT, '<strong>Artista</strong>' );

	    if( !$errorMsg )
	    {
		$artists = $this->model_artist->fetchById( $this->form_data['artists'] );
		
		// Salvo i dati completi degli artisti in sessione
		// e aggiungo il parametro openact
		foreach( $artists AS $artist )
		{
		    if( $this->form_data['artist_' . $artist['artist_id']] == 'openingact' )
		    {
			$_SESSION['Live']['Artists']['openingact'][$artist['artist_id']] = $artist;
		    }
                    else
                    {
                        $_SESSION['Live']['Artists']['main'][$artist['artist_id']] = $artist;
                    }
		}

		// Redirect...
		return header( 'Location: /admin/live/location/id/' . $this->getParam( 'id' ) );
	    }
	}
	
	# Assegniamo i dati al layout
	$this->layout->errorMsg = $errorMsg;
	$this->layout->artists = $_SESSION['Live']['Artists'];
	$this->layout->content = array( 'script' => 'live/artisti' );
    }

    public function locationAction()
    {
	if( count( $_SESSION['Live']['Artists'] ) < 1 )
	    return header( 'Location: /admin/live/artisti/id/' . $this->getParam( 'id' ) );
	
	// Edit...
	if( !empty( $this->live ) AND empty( $_SESSION['Live']['Info'] ) )
	{
	    $_SESSION['Live']['Info'] = $this->live;
	}
	
	if( $this->form_data['conferma'] AND $this->form_data['conferma'] !== '' )
	{
	    if( empty( $this->form_data['location_id'] ) )
		$errorMsg = sprintf( ERR_EMPTY_SELECT, '<strong>Location</strong>' );

	    if( !$errorMsg )
	    {
		$_SESSION['Live']['Location'] = array_shift( $this->model_location->fetchById( array( $this->form_data['location_id'] ) ) );

		// Redirect...
		return header( 'Location: /admin/live/info/id/' . $this->getParam( 'id' ) );
	    }
	}
	
	# Assegniamo i dati al layout
	$this->layout->errorMsg = $errorMsg;
	$this->layout->data	= $_SESSION['Live']['Info'];
        $this->layout->artists  = $_SESSION['Live']['Artists'];
	$this->layout->content	= array( 'script' => 'live/location' );
    }

    public function infoAction()
    {
	if( count( $_SESSION['Live']['Artists'] ) < 1 OR empty( $_SESSION['Live']['Location'] ) )
	    return header( 'Location: /admin/live/artisti/id/' . $this->getParam( 'id' ) );
	
	if( $this->form_data['conferma'] AND $this->form_data['conferma'] !== '' )
	{
	    $_SESSION['Live']['Info'] = $this->form_data;

	    // Validiamo server-side...
	    $errorMsg = $this->checkFormData( $this->form_data );

	    if( !$errorMsg )
	    {
		// Rimanda alla pagina di conferma...
		header( 'Location: /admin/live/conferma/id/' . $this->getParam( 'id' ) );
	    }
	}

	# Assegniamo i dati al layout
	$this->layout->data	= $_SESSION['Live']['Info'];
        $this->layout->artists  = $_SESSION['Live']['Artists'];
        $this->layout->location  = $_SESSION['Live']['Location'];
	
	$this->layout->errorMsg = $errorMsg;
	$this->layout->content	= array( 'script' => 'live/info' );
    }

    public function confermaAction()
    {
	if( count( $_SESSION['Live']['Info'] ) < 1 )
	    return header( 'Location: /admin/live/artisti/id/' . $this->getParam( 'id' ) );

	if( $this->form_data['salva'] AND $this->form_data['salva'] !== '' )
	{
            $live_data = $_SESSION['Live'];
            
            // Mapping...
            $data = array(
                'live_id' => $this->live['live_id'],
                'live_location_id' => $live_data['Location']['location_id'],
                'live_status_id' => $live_data['Info']['live_status_id'],
                'live_ispublic' => $live_data['Info']['live_ispublic'],
                'live_date' => $live_data['Info']['live_date_y'] . '-' . $live_data['Info']['live_date_m'] . '-' . $live_data['Info']['live_date_d'],
                'live_stagetime' => $live_data['Info']['live_stagetime_h'] . ':' . $live_data['Info']['live_stagetime_m'],
                'live_doorsopen' => $live_data['Info']['live_doorsopen_h'] != '' ? $live_data['Info']['live_doorsopen_h'] . ':' . $live_data['Info']['live_doorsopen_m'] : null,
                'live_loadin' => $live_data['Info']['live_loadin_h'] != '' ? $live_data['Info']['live_loadin_h'] . ':' . $live_data['Info']['live_loadin_m'] : null,
                'live_soundcheck' => $live_data['Info']['live_soundcheck_h'] != '' ? $live_data['Info']['live_soundcheck_h'] . ':' . $live_data['Info']['live_soundcheck_m'] : null,
                'live_price' => $live_data['Info']['live_price_1'] != '' ? $live_data['Info']['live_price_1'] . ',' . $live_data['Info']['live_price_2'] : '',
                'live_notes' => $live_data['Info']['live_notes']
            );

            // Edit o Aggiunta?
	    if( !empty( $this->live ) )
		$data['live_modifiedby'] = $this->application->auth->user['user_id'];
	    else
		$data['live_createdby'] = $this->application->auth->user['user_id'];

            $model = new Classes_Live( $data );

            $extra = $_SESSION['Live'];
            
            if( is_numeric( $live_id = $model->save( $extra )->live_id ) )
            {
                unset( $_SESSION['Live'] );
                
                // Redirect...
                return header( 'Location: /admin/live/riepilogo/id/' . $live_id );
            }
            else
            {
                $errorMsg = $model->errors;
                
                if( $model->errors['live_notes'] )
                    $errorMsg['live_notes'] = sprintf( ERR_FORMAT, 'Note' );

                if( $model->errors['live_date'] )
                    $errorMsg['live_date'] = ERR_DATE;

                if( $model->errors['live_stagetime'] )
                    $errorMsg['live_stagetime'] = ERR_DATE;

                if( $model->errors['live_price'] )
                    $errorMsg['live_price'] = sprintf( ERR_FORMAT, 'Ingresso' );

                if( $model->errors['live_doorsopen'] )
                    $errorMsg['live_doorsopen'] = ERR_DATE;

                if( $model->errors['live_loadin'] )
                    $errorMsg['live_loadin'] = ERR_DATE;
            }
	}        
        
//	if( $this->form_data['conferma'] AND $this->form_data['conferma'] !== '' )
//	{
//	    $live_data = $_SESSION['Live'];
//
//	    // Preparo l'array sa spedire al model..
//            # Mapping...
//            $data = array(
//                'live_id' => $this->live['live_id'],
//                'live_location_id' => $live_data['Location']['location_id'],
//                'live_status_id' => $live_data['Info']['live_status_id'],
//                'live_ispublic' => $live_data['Info']['live_ispublic'],
//                'live_date' => $live_data['Info']['live_date_y'] . '-' . $live_data['Info']['live_date_m'] . '-' . $live_data['Info']['live_date_d'],
//                'live_stagetime' => $live_data['Info']['live_stagetime_h'] . ':' . $live_data['Info']['live_stagetime_m'],
//                'live_doorsopen' => $live_data['Info']['live_doorsopen_h'] != '' ? $live_data['Info']['live_doorsopen_h'] . ':' . $live_data['Info']['live_doorsopen_m'] : null,
//                'live_loadin' => $live_data['Info']['live_loadin_h'] != '' ? $live_data['Info']['live_loadin_h'] . ':' . $live_data['Info']['live_loadin_m'] : null,
//                'live_soundcheck' => $live_data['Info']['live_soundcheck_h'] != '' ? $live_data['Info']['live_soundcheck_h'] . ':' . $live_data['Info']['live_soundcheck_m'] : null,
//                'live_price' => $live_data['Info']['live_price_1'] != '' ? $live_data['Info']['live_price_1'] . ',' . $live_data['Info']['live_price_2'] : '',
//                'live_notes' => $live_data['Info']['live_notes']
//            );
//
//            // Edit o Insert?
//	    if( !empty( $this->live ) )
//		$data['live_modifiedby'] = $this->application->auth->user['user_id'];
//	    else
//		$data['live_createdby'] = $this->application->auth->user['user_id'];
//            
//	    $model = new Classes_Live( $data );
//
//	    // Inizio transazione...
//	    $this->model_live->beginTransaction();
//
//	    if( is_numeric( $live_id = $model->save()->live_id ) )
//	    {
//		foreach( $live_data['Artists']['main'] AS $artist )
//		{
//		    $live_artists[] = array( 'fab_artists_artist_id' => $artist['artist_id'], 'openingact' => 0 );
//		}
//                
//		foreach( $live_data['Artists']['openingact'] AS $artist )
//		{
//		    $live_artists[] = array( 'fab_artists_artist_id' => $artist['artist_id'], 'openingact' => 1 );
//		}
//
//		$model_live_artists = new Classes_LiveArtist( array( 'fab_live_live_id' => $live_id ) );
//		
//		if( $model_live_artists->saveLive( $live_artists ) === TRUE )
//		{
//		    // Commit!
//		    $this->model_live->commit();		    
//
//		    unset( $_SESSION['Live'] );
//                    
//                    // Rimanda alla pagina di conferma...
//                    header( 'Location: /admin/live/riepilogo/id/' . $live_id );
//		    
//		    return ;
//		}
//		else
//		{
//		    $this->model_live->rollBack();
//		}
//	    }
//	    else
//	    {
//                $errorMsg = ( $model->errors );
//		$this->model_live->rollBack();
//		trigger_error( 'Errore Inserimento Live' );
//	    }
//	}

	# Assegniamo i dati al layout
	$this->layout->data		= $_SESSION['Live']['Info'];
        $this->layout->artists          = $_SESSION['Live']['Artists'];
        $this->layout->location         = $_SESSION['Live']['Location'];
	$this->layout->data['live_id']	= $this->live['live_id'];

	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'live/conferma' );
    }
    
    public function riepilogoAction()
    {
	if( empty( $this->live ) )
	    trigger_error( 'Nessun live Selezionato' );
        
        # Formattiamo campi
        list( $this->live['live_date_d'], $this->live['live_date_m'], $this->live['live_date_y'] )	    = explode( '-', $this->live['live_date_ita'] );
        list( $this->live['live_stagetime_h'], $this->live['live_stagetime_m'] )    = explode( 'h', $this->live['live_stagetime'] );
        list( $this->live['live_loadin_h'], $this->live['live_loadin_m'] )          = explode( 'h', $this->live['live_loadin'] );
        list( $this->live['live_soundcheck_h'], $this->live['live_soundcheck_m'] )  = explode( 'h', $this->live['live_soundcheck'] );
        list( $this->live['live_doorsopen_h'], $this->live['live_doorsopen_m'] )    = explode( 'h', $this->live['live_doorsopen'] );
        list( $this->live['live_price_1'], $this->live['live_price_2'] )	    = explode( ',', $this->live['live_price'] );

        # Assegniamo i dati al layout
	$this->layout->live		= $this->live;
        $this->layout->content = array( 'script' => 'live/riepilogo' );
    }

    public function postAction()
    {
        if( empty( $this->live ) )
	    trigger_error( 'Nessun live Selezionato' );

        if( !empty( $this->live['post']['post_id'] ) )
        {
            $this->post = array_shift( $this->model_post->fetchById( array( $this->live['post']['post_id'] ) ) );
        }

        $form_data = $this->getParams();

        if( $form_data['conferma'] AND $form_data['conferma'] !== '' )
	{
            $this->layout->data = $form_data;

            foreach( $this->live['artists']['main'] as $artist )
                $post_title .= $artist['artist_name'] .', ';
            
            $post_title = substr( $post_title, 0, -2 );
            
            if( count( $this->live['artists']['openingact'] ) )
            {
                $post_title = $post_title .' + ';
                foreach( $this->live['artists']['openingact'] as $artist )
                    $post_title .= $artist['artist_name'] .' - ';
            }
            
            $post_title = $this->live['live_date_ita'] .' '. substr( $post_title, 0, -3 ) .' @ '. $this->live['location']['location_name'] .' ('. $this->province[$this->live['location']['location_province_id']]['province_short_name'] .')';
            
            // Mapping...
            $data = array(
                'post_id'               => $this->post['post_id'],
                'post_title'            => $post_title,
                'post_text'             => $form_data['post_text'],
                'post_tags'             => $form_data['post_tags'],
                'post_published'        => $form_data['year'] . '-' . $form_data['month'] . '-' . $form_data['day'],
                'post_live_id'          => $this->live['live_id']
            );

            // Edit o Aggiunta?
            if( empty( $this->post['post_id'] ) )
                $data['post_createdby'] = $this->application->auth->user['user_id'];
            else
                $data['post_modifiedby'] = $this->application->auth->user['user_id'];

            $model = new Classes_Post( $data );

            if( is_numeric( $post_id = $model->save( )->post_id ) )
            {
                // Redirect...
                return header( 'Location: /admin/live/postlinks/id/'. $this->live['live_id'] );
                
            }
            else
            {
                if( $model->errors['post_title'] )
                    $errorMsg['post_title'] = sprintf( ERR_FORMAT, 'Titolo' );

                if( $model->errors['post_text'] )
                    $errorMsg['post_text'] = ERR_EMPTY;

                if(  $model->errors['post_published'] )
                    $errorMsg['post_published'] = ERR_DATE;

            }   
        }        

        # Assegniamo i dati al layout
	$this->layout->live		= $this->live;
        $this->layout->errorMsg         = $errorMsg;
        $this->layout->content = array( 'script' => 'live/post' );        
    }

    public function postlinksAction()
    {
        if( empty( $this->live ) )
	    trigger_error( 'Nessun live Selezionato' );
        
        if( empty( $this->live['post']['post_id'] ) )
        {
            return header( 'Location: /admin/live/post/id/' . $this->live['live_id'] ); // Redirect...
        }
        else
        {
            $this->post = array_shift( $this->model_post->fetchById( array( $this->live['post']['post_id'] ) ) );
        }

        $form_data = $this->getParams();
        
        if( $form_data['conferma'] AND $form_data['conferma'] !== '' )
	{
            if( count( $form_data['post_links'] ) )
            {
                foreach( $form_data['post_links'] as $k => $post_link )
                {
                    $post_links[] = array( 'link_post_id' => $this->post['post_id'], 'link_url' => $post_link, 'link_desc' => $form_data['post_link_desc'][$k] );
                }
            }

            // Mapping...
            $data = array(
                'post_id'               => $this->post['post_id']
            );
            
            $model = new Classes_Post( $data );
            
            if( is_numeric( $post_id = $model->saveExtra( array( 'post_links' => $post_links ) )->post_id ) AND !$model->errors )
            {
		// Rimanda alla pagina di conferma e cancella file temporanei...
		$this->layout->forward = 'partners/archivio';

		return $this->layout->content = array( 'script' => 'completed' );
            }
            else
            {
                if( $model->errors )
                    $errorMsg['post_link'] = sprintf( ERR_FORMAT, '<b>Url</b>' );
            }
        }
        
        # Assegniamo i dati al layout
        $this->layout->errorMsg = $errorMsg;
	$this->layout->live	= $this->live;
        $this->layout->post	= $this->post;
        $this->layout->content  = array( 'script' => 'live/postlinks' );        
    }
    
    public function rassegneAction()
    {
	if( empty( $this->live ) )
	    trigger_error( 'Nessun live Selezionato' );

	$form_data = $this->getParams();
	
	if( !empty( $form_data['conferma'] ) )
	{
	    $events = array();
    
	    if( is_array( $form_data['events'] ) AND !empty( $form_data['events'] ) )
	    {
		foreach( $form_data['events'] AS $key => $value )
		{
		    // Mapping...
		    $events[] = array( 'fab_events_event_id' => $value );
		}
	    }

	    $model = new Classes_EventLive( array( 'fab_live_live_id' => $this->live['live_id'] ) );

	    if(  $model->saveLive( $events ) === TRUE )
	    {
		// Rimanda alla pagina di conferma e cancella file temporanei...
		$this->layout->forward = 'partners/archivio';

		return $this->layout->content = array( 'script' => 'completed' );
	    }
	    else
	    {
		trigger_error( 'Errore Aggiunta Evento/Live' );
	    }

	    $this->layout->data = $form_data;
	}
	
	# Assegniamo i dati al layout
	# Formattiamo campi
	list( $this->live['day'], $this->live['month'], $this->live['year'] )	    = explode( '-', $this->live['live_date'] );
	list( $this->live['live_start_time_h'], $this->live['live_start_time_m'] )  = explode( ':', $this->live['live_start_time'] );
	list( $this->live['live_gate_open_h'], $this->live['live_gate_open_m'] )    = explode( ':', $this->live['live_gate_open'] );
	list( $this->live['live_price_1'], $this->live['live_price_2'] )	    = explode( ',', $this->live['live_price'] );

	// Format Data
	$this->layout->data['start_day'] = $this->days[date( 'N', mktime( $hour, $minute, $second, $this->live['month'], $this->live['day'], $this->live['year'] ) )];

	// Separiamo i Main dagli Open-Act (solo per visualizzazione)
	
	$this->layout->location = array_shift( $this->model_location->fetchById( array( $this->live['live_location_id'] ) ) );	
	
	$this->layout->data = $this->live;
	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'live/rassegne' );	
    }

    public function vediAction()
    {
        if( empty( $this->live ) )
        {
            trigger_error( 'Errore Vedi Live' );
        }
        
	// Format Data
        list( $this->live['day'], $this->live['month'], $this->live['year'] )	    = explode( '-', $this->live['live_date_ita'] );

	# Assegniamo i dati al layout
	$this->layout->data		= $this->live;
	$this->layout->data['live_id']	= $this->live['live_id'];

	$this->layout->errorMsg = $errorMsg;
        $this->layout->content = array( 'script' => 'live/vedi' );      
    }


    private function checkFormData( $data )
    {
	if( $data['live_notes'] != '' AND !filter_var( $data['live_notes'], FILTER_SANITIZE_STRING ) )
	    $errorMsg['live_notes'] = sprintf( ERR_FORMAT, 'Note' );

	if( !checkdate( $data['live_date_m'], $data['live_date_d'], $data['live_date_y'] ) )
	    $errorMsg['live_date'] = ERR_DATE;

	if( !is_numeric( $data['live_stagetime_h'] ) OR !is_numeric( $data['live_stagetime_m'] ) )
	    $errorMsg['live_stagetime'] = ERR_DATE;

	if( $data['live_price_1'] != '' AND !filter_var( $data['live_price_1'], FILTER_VALIDATE_INT ) )
	    $errorMsg['live_price'] = sprintf( ERR_FORMAT, 'Ingresso' );

	if( ( $data['live_doorsopen_h'] != '' OR $data['live_doorsopen_m'] != '' ) AND (!is_numeric( $data['live_doorsopen_h'] ) OR !is_numeric( $data['live_doorsopen_m'] ) ) )
	    $errorMsg['live_dooropen'] = ERR_DATE;

	if( ( $data['live_loadin_h'] != '' OR $data['live_loadin_m'] != '' ) AND (!is_numeric( $data['live_loadin_h'] ) OR !is_numeric( $data['live_loadin_m'] ) ) )
	    $errorMsg['live_dooropen'] = ERR_DATE;


	return $errorMsg ? $errorMsg : false;
    }
    
    private function checkFormLinks( $data )
    {
	if( !filter_var_array( $data['post_link'], FILTER_VALIDATE_URL ) )
	    $errorMsg['post_link'] = sprintf( ERR_URL, 'Titolo' );

	/* Info Opzionali */
	if( !empty( $data['post_link_desc'] ) AND !filter_var_array( $data['post_link_desc'], FILTER_VALIDATE_URL ) )
	    $errorMsg['post_link_desc'] = sprintf( ERR_URL, 'Note' );
	
	return $errorMsg ? $errorMsg : false;
    }    
}